﻿using System;
using System.Collections.Generic;

namespace Flagwind.Options.Configuration
{
	public class ConnectionStringElementCollection : OptionConfigurationElementCollection<ConnectionStringElement>, ISettingsProvider
	{
		#region 构造方法

		public ConnectionStringElementCollection() : base("connectionString")
		{
		}

		#endregion

		#region 重写方法

		protected override OptionConfigurationElement CreateNewElement()
		{
			return new ConnectionStringElement();
		}

		protected override string GetElementKey(OptionConfigurationElement element)
		{
			return ((ConnectionStringElement)element).Name;
		}

		#endregion

		#region 接口实现

		object ISettingsProvider.GetValue(string name)
		{
			if(string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			return this[name];
		}

		void ISettingsProvider.SetValue(string name, object value)
		{
			if(string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			string text, provider = null;

			if(value is string)
			{
				text = (string)value;
			}
			else if(value is ConnectionStringElement)
			{
				text = ((ConnectionStringElement)value).Value;
				provider = ((ConnectionStringElement)value).Provider;
			}
			else if(value is SettingElement)
			{
				text = ((SettingElement)value).Value;
			}
			else
				throw new InvalidOperationException("Unsupported value type.");

			if(this.ContainsKey(name))
			{
				this[name].Value = text;

				if(provider != null)
					this[name].Provider = provider;
			}
			else
			{
				this.Add(new ConnectionStringElement(name, text, provider));
			}
		}

		#endregion
	}
}